import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.objectweb.asm.*;

import IL.ClassGenerator;
import IL.MethodGenerator;

public class BytecodeParser {

	public String className;
	String fileFullName;
	String outputDir;
	
	BytecodeParser(String path,String name) {
		className = name;
		fileFullName = new String(path+"/"+className);
		outputDir = "c:/output/";
	}

	void parseAndConvert() {
		
		ClassReader cr;
		try {
			File file = new File(fileFullName);
			FileInputStream fin = new FileInputStream(file);
			byte fileContent[] = new byte[(int)file.length()];
			
			fin.read(fileContent);
			cr = new ClassReader(fileContent);
			ClassWriter cw = new ClassWriter(cr,0);
			MyClassAdapter ca = new MyClassAdapter(cw, className);
			cr.accept(ca, 0);
			
			// printInConsole(ca.cg);
			// printIL(ca.cg);
			printILtoFile(ca.cg);
		} 
		catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
	
	
	void printIL(ClassGenerator cg)
	{
		List<String> header = cg.prepareClassHeader();
		List<String> footer = cg.prepareClassFooter();
		
		for(String h: header){
			System.out.println(h);
		}
		
		for(MethodGenerator mg: cg.methodGeneratorList)
		{
			for(String s: mg.methInstructions) {
				System.out.println(s);
			}
		}
		
		for(String f: footer){
			System.out.println(f);
		}
	}
	
	void printInConsole(ClassGenerator cg)
	{
		
	}
	
	void printILtoFile(ClassGenerator cg)
	{
		if(!className.endsWith(".class")) 
			return;
		
		String clsName = className.substring(0, className.length()-6);
			
		File fout = new File(outputDir + clsName + ".il");
		BufferedWriter output;
		
		try {
			FileWriter fStream = new FileWriter(fout);
			output = new BufferedWriter(fStream);
				
			List<String> header = new ArrayList<String>();
			header.addAll(cg.prepareClassHeader());
			header.addAll(cg.prepareClassDeclarationString());
			
			for(String h: header){
				output.write(h);
			}
			
			if(!(cg.cls.isInterface && cg.cls.isAbstract))
			{
				for(MethodGenerator mg: cg.methodGeneratorList)
				{
					for(String s: mg.methInstructions) {
						output.write(s);
					}
				}
			}

			List<String> footer = new ArrayList<String>();
			footer.addAll(cg.prepareClassFooter());
			
			for(String f: footer){
				output.write(f);
			}

			output.close();
		}
		catch (IOException e) {
			e.printStackTrace();
		}
		
		
	}
}



